//
//  LCHTMLBaseViewController.m
//  JKFuYinProject
//
//  Created by admin on 2018/6/25.
//  Copyright © 2018年 LC. All rights reserved.
//

#import "LCHTMLBaseViewController.h"

@interface LCHTMLBaseViewController ()

@end

@implementation LCHTMLBaseViewController

- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    for (NSInteger i = 0; i < _scriptNameArr.count; i++) {
        [self.webView.configuration.userContentController addScriptMessageHandler:self name:_scriptNameArr[i]];
    }
}
- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    for (NSInteger i = 0; i < _scriptNameArr.count; i++) {
        [self.webView.configuration.userContentController removeScriptMessageHandlerForName:_scriptNameArr[i]];
    }
    [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillShowNotification object:nil];
}
- (void)dealloc {
    @try {
        [_webView removeObserver:self forKeyPath:@"estimatedProgress"];
    } @catch (NSException *exception) { }
}
- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor whiteColor];
    [self setupWebView];
    [self setupWebViewToolBar];
    [self setupProgressView];
}
#pragma - mark      ---------- 创建WebView ----------
/**
 *  创建WebView
 */
- (void)setupWebView {
    self.edgesForExtendedLayout = UIRectEdgeNone;
    self.tabBarController.tabBar.translucent = NO;

    WKWebViewConfiguration *config = [[WKWebViewConfiguration alloc] init];
    WKWebView *webView = [[WKWebView alloc] initWithFrame:self.view.frame configuration:config];
    self.webView = webView;
    [self.view addSubview:self.webView];

    self.webView.scrollView.bounces = NO;//禁止WebView滚动和回弹方法
    self.webView.UIDelegate = self;
    self.webView.navigationDelegate = self;
    if (@available(iOS 11.0, *)) {
        self.webView.scrollView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
    }else{
        self.automaticallyAdjustsScrollViewInsets = NO;
    }
    [self.webView addObserver:self forKeyPath:@"estimatedProgress" options:NSKeyValueObservingOptionNew context:nil];
    NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:@"%@",_link]];//创建URL
    NSURLRequest *request = [[NSURLRequest alloc] initWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:5.0f];//创建NSURLRequest
    [self.webView loadRequest:request];//加载

    [self setupWebViewLayout];
}
- (void)setupWebViewLayout
{
    if (self.isShowToolBar) {
        self.webView.sd_layout.leftSpaceToView(self.view, 0).rightSpaceToView(self.view, 0).topSpaceToView(self.view, 0).bottomSpaceToView(self.view, 50 + TAB_BAR_HEIGHT - 49);
    }else {
        self.webView.sd_layout.leftSpaceToView(self.view, 0).rightSpaceToView(self.view, 0).topSpaceToView(self.view, 0).bottomSpaceToView(self.view, 0 + TAB_BAR_HEIGHT - 49);
    }
}
- (void)setupProgressView {
    self.progressView = [[LCProgressView alloc] initWithFrame:CGRectMake(0, 0, ScreenWidth, 2)];
    [self.view addSubview:self.progressView];
    [self.view bringSubviewToFront:self.progressView];
    [self.progressView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.webView).offset(0);
        make.left.right.equalTo(self.view);
        make.height.mas_equalTo(2);
    }];
}

- (void)setupWebViewToolBar {
    _customToolBar = [[LCWebViewToolBar alloc] init];
    [self.view addSubview:_customToolBar];
    if (self.isShowToolBar) {
        [_customToolBar mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.right.equalTo(self.view);
            make.height.mas_equalTo(50);
            if (@available(iOS 11.0, *)) {
                make.bottom.equalTo(self.view.mas_safeAreaLayoutGuideBottom);
            } else {
                make.bottom.equalTo(self.view.mas_bottom);
            }
        }];
    }else{
        _customToolBar.hidden = YES;
        [_customToolBar mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.right.equalTo(self.view);
            make.height.mas_equalTo(0);
            if (@available(iOS 11.0, *)) {
                make.bottom.equalTo(self.view.mas_safeAreaLayoutGuideBottom);
            } else {
                make.bottom.equalTo(self.view.mas_bottom);
            }
        }];
    }
}
/**
 *  配置前进的按钮是否可点击
 */
- (void)setGoForwardItem {
    [_customToolBar setIsGoNext:[self.webView canGoForward]];
}
/**
 *  将要开始加载
 */
- (void)webView:(WKWebView *)webView decidePolicyForNavigationAction:(WKNavigationAction *)navigationAction decisionHandler:(void (^)(WKNavigationActionPolicy))decisionHandler {
    NSLog(@"class == %@  line == %d  func == %s", [self class], __LINE__, __FUNCTION__);
    // 配置前进的按钮是否可点击
    [self setGoForwardItem];
    
    NSString *url = [navigationAction.request.URL.absoluteString stringByRemovingPercentEncoding];
    if ([url containsString:@"https://itunes.apple.com/cn/app/"]){
        [NSURL SafariOpenURL:navigationAction.request.URL];
        decisionHandler(WKNavigationActionPolicyAllow);
        return;
    }
    if(self.shouldStartLoadBlock != nil) {
        self.shouldStartLoadBlock(url);
        if (_isLoad == NO) {
            decisionHandler(WKNavigationActionPolicyCancel);
            return;
        }else {
            decisionHandler(WKNavigationActionPolicyAllow);
            return;
        }
    }
    decisionHandler(WKNavigationActionPolicyAllow);
}
/**
 *  加载完成
 */
- (void)webView:(WKWebView *)webView didFinishNavigation:(WKNavigation *)navigation {
    NSLog(@"class == %@  line == %d  func == %s", [self class], __LINE__, __FUNCTION__);
    // 配置前进的按钮是否可点击
    [self setGoForwardItem];
    self.link = [webView.URL absoluteString];
    [self getHtmlTitle:self.webView.title];
//    NSString *allHtmlJSString = @"document.getElementsByClassName('content')";//.innerHTML
//    __weak typeof(self) weakSelf = self;
//    [self.webView evaluateJavaScript:allHtmlJSString completionHandler:^(id _Nullable result, NSError * _Nullable error) {
//        [weakSelf getHtmlContent:result];
//    }];
}
/**
 *  加载失败
 *
 *  @param webView 正在加载的webView虚拟对象，如果需要用到webView，就用这个对象加载 getWebView 这个方法
 *  @param error   失败的对象
 */
- (void)webView:(WKWebView *)webView didFailProvisionalNavigation:(null_unspecified WKNavigation *)navigation withError:(NSError *)error {
    NSLog(@"class == %@  line == %d  func == %s", [self class], __LINE__, __FUNCTION__);
    // 配置前进的按钮是否可点击
    [self setGoForwardItem];
    self.link = [webView.URL absoluteString];
    [self getHtmlTitle:self.webView.title];
}
/**
 *  获取当前加载的网页标题
 */
- (void)getHtmlTitle:(NSString *)title {
    self.title = title;
    NSLog(@"class == %@  line == %d  func == %s", [self class], __LINE__, __FUNCTION__);
}
/**
 *  获取当前加载的网页内容
 */
- (void)getHtmlContent:(NSString *)content {
    NSLog(@"class == %@  line == %d  func == %s", [self class], __LINE__, __FUNCTION__);
}

/**
 *  正在加载
 */
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSString *,id> *)change context:(void *)context {
    if ([keyPath isEqualToString:@"estimatedProgress"]) {
        [self webViewDidStartLoad];
        [self.progressView setProgress:self.webView.estimatedProgress animated:YES];

        if (self.webView.estimatedProgress < 1.0) {
            self.progressView.delayTime = 1 - self.webView.estimatedProgress;
            return;
        }
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(self.progressView.delayTime * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            self.progressView.progress = 0;
        });
    }
}
/**
 *  正在加载
 */
- (void)webViewDidStartLoad {
    self.title = @"加载中...";
}

- (void)userContentController:(WKUserContentController *)userContentController
      didReceiveScriptMessage:(WKScriptMessage *)message{
    //    NSLog(@"JS 调用了 %@ 方法，传回参数 %@",message.name,message.body);
    for (NSInteger i = 0; i < _scriptNameArr.count; i++) {
        if([message.name isEqualToString:_scriptNameArr[i]]) {
            [self lcJavaScriptInteractionWithReceiveScriptMessage:message];
        }
    }
}
- (void)lcJavaScriptInteractionWithReceiveScriptMessage:(WKScriptMessage *)message{
    
}
/////禁止键盘弹出时WKWebView自动滑动
//- (UIView *)viewForZoomingInScrollView:(UIScrollView *)scrollView {
//    return nil;
//}
- (WKWebView *)webView:(WKWebView *)webView createWebViewWithConfiguration:(WKWebViewConfiguration *)configuration forNavigationAction:(WKNavigationAction *)navigationAction windowFeatures:(WKWindowFeatures *)windowFeatures {
    if (!navigationAction.targetFrame.isMainFrame) {
        [webView loadRequest:navigationAction.request];
    }
    return nil;
}

@end
